﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Script.Serialization;

namespace Twi.COMMON.Core
{
    /*
    * Copyright: ©2010 ©2010-2011 Twilight软件开发工作室版权所有
    * Author: xuzhihong
    * Create date: 2010-4-22
    * Description: 统一序列化为json对象
    * 
    */
    public partial class JSSerialize
    {
        /// <summary>
        /// 泛型序列化静态方法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        public static string Serialize<T>(T t)
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();
            string str = "";
            try
            {
                str = jss.Serialize(t);
            }
            catch (System.Exception ex)
            {
            	if (t is TwiReturn)
            	{
                    TwiReturn twi = TwiReturn.Clone(t as TwiReturn);
                    twi.data = ex.Message;//"[ToString]"+twi.data;
                    try
                    {
                        str = jss.Serialize(twi);
                    }
                    catch { 
                       //再序列化错误就返回""了
                    }
            	}
            	else
                {
                    str ="数据序列化错误："+ex.Message; 
            	}
            }
            return str;
        }

        /// <summary>
        /// 泛型 反序列化静态方法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="str"></param>
        /// <returns></returns>
        public static T Deserialize<T>(string str)
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();
            return jss.Deserialize<T>(str);
        }

    }
}
